package com.restkeeper.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.dto.DyUsersDto;
import com.restkeeper.entity.DyUsers;
import com.restkeeper.mapper.DyUsersMapper;
import com.restkeeper.service.CommonService;
import com.restkeeper.service.DyUsersService;
import com.restkeeper.utils.Result;
import com.alibaba.fastjson.JSONObject;
import com.restkeeper.vo.DyUsersVo;
import com.restkeeper.vo.UserInfoResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DyUsersServiceImpl extends ServiceImpl<DyUsersMapper, DyUsers> implements DyUsersService {

    @Autowired
    private CommonService commonService;

    @Override
    public Result login(DyUsersDto dyUsersDto) {
        String code = dyUsersDto.getCode();
        if (code == null) {
            return Result.error("登录 code 不能为空");
        }

        // 通过 code 获取用户基本信息
        JSONObject basicUserInfo = commonService.getDouyinUserBasicInfoByCode(code);
        if (basicUserInfo == null) {
            return Result.error("获取抖音用户基本信息失败");
        }

        // 从返回的用户信息中获取 openid 和 access_token
        String openid = basicUserInfo.getString("openid");
        String unionid = basicUserInfo.getString("unionid");
        String accessToken = basicUserInfo.getString("access_token"); // 假设接口返回了 access_token
        if (openid == null) {
            return Result.error("未获取到用户 openid");
        }

//        // 获取用户详细信息
//        UserInfoResponse detailUserInfo = commonService.getDouyinUserDetailInfo(openid, accessToken);
//        if (detailUserInfo == null) {
//            return Result.error("获取抖音用户详细信息失败");
//        }

        // 校验用户是否存在
        DyUsers existingUser = this.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<DyUsers>().eq("openid", openid));
        if (existingUser == null) {
            // 用户不存在，新增用户
            DyUsers newUser = new DyUsers();
            newUser.setOpenid(openid);
            // 填充更多用户信息
//            newUser.setNickName(detailUserInfo.getString("nickname"));
            newUser.setUnionid(unionid);
//            newUser.setAvatarUrl(detailUserInfo.getString("avatar_url"));
            // 可以根据实际返回的字段继续填充其他信息
            this.save(newUser);
            existingUser = newUser;
        } else {
            // 用户存在，更新用户信息
//            existingUser.setNickName(detailUserInfo.getString("nickname"));
//            existingUser.setAvatarUrl(detailUserInfo.getString("avatar_url"));
//            this.updateById(existingUser);
        }

        // 将用户信息转换为 DTO 返回给前端
        DyUsersVo vo = new DyUsersVo();
        BeanUtils.copyProperties(existingUser, vo);
        return Result.ok(vo);
    }

}